//
//  CTMediator+ConnectionAction.m
//  at_xiaoge_client
//
//  Created by Linyu Niu on 06/03/2018.
//  Copyright © 2018 Linyu Niu. All rights reserved.
//

#import "CTMediator+ConnectionAction.h"

NSString * token = nil;


NSString * const  kCTMediatorConnectionTarget                                         = @"Connection";
NSString * const  kCTMediatorConnectionAction                                         = @"postData";


@implementation CTMediator(ConnectionAction)


-(instancetype)init{
    self = [super init];
    
    return self;
}

-(void)setToken:(NSString *)tokenValue{
    token = tokenValue;
}
-(void)clearUserData{
    
    token = nil;
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"UserId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"UserToken"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"UserData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kReloadMyInfoNotification" object:nil];
}



-(void)getTokenWithTokentype:(NSString *)type block:(void(^)(NSDictionary *dic))block
{
    token = nil;
    if (type && ![@"" isEqualToString:type]) {
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        [params setObject:type forKey:@"tokentype"];
        [self excuteAction:params urlMethod:@"gaintoken.json" block:block];
    }
}

-(void)sendMessageWithType:(NSString *)type mobile:(NSString *)mobile block:(void(^)(NSDictionary *dic))block{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    if (mobile) {
        [params setObject:[mobile stringByReplacingOccurrencesOfString:@" " withString:@""] forKey:@"mobile"];
    }
    if (type) {
        [params setObject:type forKey:@"smstype"];
    }
    
    if (token) {
        [params setObject:token forKey:@"macToken"];
    }
    
#if kDevelopment
    [params setObject:@"test" forKey:@"testIs"];
    
#endif
    [self excuteAction:params urlMethod:@"sendSMS.json" block:block];
}



-(void)getUserInfo:(void (^)(NSDictionary *))block{
    [self excuteAction:nil urlMethod:@"gainUserInfo.json" block:block];
}

-(void)uploadUserHeadImage:(UIImage *)img userId:(NSString *)userId registIs:(BOOL)registIs block:(void(^)(NSDictionary * dic))block{
    NSData * imgData = UIImageJPEGRepresentation(img, 1.0);
    NSString * base64String = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setNLYObjectForKey:base64String forKey:@"headPortraitBase64"];
    [params setObject:@"jpg" forKey:@"imageType"];
    [params setObject:@"0" forKey:@"registIs"];
    if (registIs) {
        [params setObject:@"1" forKey:@"registIs"];
    }
    [params setNLYObjectForKey:userId forKey:@"courierId"];
    
    
    [self excuteAction:params urlMethod:@"uploadCourierHeadPortrait.json" block:block];
//    [self excuteAction:params urlMethod:@"changeUserHeadPortrait.json" block:block];
}
-(void)registerOrLogin:(NSString *)mobile code:(NSString *)code pwd:(NSString *)pwd block:(void(^)(NSDictionary *dic))block{
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setNLYObjectForKey:code forKey:@"valiCode"];
    [params setNLYObjectForKey:[mobile stringByReplacingOccurrencesOfString:@" " withString:@""] forKey:@"mobile"];
    
    [params setNLYObjectForKey:[pwd md5] forKey:@"password"];
    [self excuteAction:params urlMethod:@"registerCourierSubmit.json" block:block];
}

-(void)getCourierLatestExpressByNumber:(NSString *)expressNumber block:(void(^)(NSDictionary *dic))block{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:expressNumber,@"expressNo", nil];
    [self excuteAction:dic urlMethod:@"courier/getCourierLatestExpress.json" block:block];
}

-(void)bindCourierExpressNo:(NSString *)couierID registIs:(NSInteger)registIs expressNO:(NSString *)expressNO expressId:(NSString *)expressId block:(void(^)(NSDictionary *dic))block
{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setNLYObjectForKey:couierID forKey:@"courierId"];
    [dic setNLYObjectForKey:expressId forKey:@"expressId"];
    [dic setNLYObjectForKey:[NSNumber numberWithInteger:registIs].stringValue forKey:@"registIs"];
    [dic setNLYObjectForKey:expressNO forKey:@"expressNO"];
    [self excuteAction:dic urlMethod:@"bindCourierExpressNo.json" block:block];
}
-(void)uploadIDCard:(NSString *)type image:(UIImage *)img cardNumber:(NSString *)number name:(NSString *)name courierId:(NSString *)courierId registIs:(NSInteger)registIs block:(void(^)(NSDictionary *dic))block{
    if (img) {
        NSData * imgData = UIImageJPEGRepresentation(img, 1.0);
        NSString * base64String = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSMutableDictionary * param = [NSMutableDictionary dictionary];
        [param setNLYObjectForKey:type forKey:@"cardzf"];
        [param setNLYObjectForKey:number forKey:@"cardId"];
        
        [param setObject:@"jpg" forKey:@"imageType"];
        [param setObject:name forKey:@"courierName"];
        [param setNLYObjectForKey:base64String forKey:@"cardIdImgBase64"];
        [param setNLYObjectForKey:courierId forKey:@"courierId"];
        [param setNLYObjectForKey:[NSNumber numberWithInteger:registIs].stringValue forKey:@"registIs"];
        
        [self excuteAction:param urlMethod:@"changeCourierCardId.json" block:block];
    }
}
-(void)login:(NSString *)mobile pwd:(NSString *)pwd block:(void(^)(NSDictionary *dic))block{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setNLYObjectForKey:mobile forKey:@"mobile"];
    [dic setNLYObjectForKey:[pwd md5] forKey:@"password"];
    [self excuteAction:dic urlMethod:@"loginSubmit.json" block:block];
}

-(void)getCourierState:(NSString *)userId block:(void(^)(NSDictionary *dic))block{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:userId,@"courierId", nil];
    [self excuteAction:dic urlMethod:@"getCourierState.json" block:block];
}

-(void)messageListblock:(void(^)(NSDictionary *dic))block{
    NSDictionary * dic = [NSDictionary dictionary];
    [self excuteAction:dic urlMethod:@"courier/messageList.json" block:block];
}
-(void)getMyWalletData:(void(^)(NSDictionary *dic))block{
//
    
    [self excuteAction:[self wrapSignParams:nil] urlMethod:@"courier/myWallet.json" block:block];
}

-(void)getWalletDetail:(NSString *)accountId  block:(void(^)(NSDictionary *dic))block{
    //
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:accountId,@"accountId", nil];
    [self excuteAction:[self wrapSignParams:dic] urlMethod:@"courier/myWalletDetailList.json" block:block];
}



//上班
-(void)onDutyDeal:(void(^)(NSDictionary *dic))block{
    [self excuteAction:[self wrapSignParams:nil] urlMethod:@"courier/onDutyDeal.json" block:block];
}
//下班

-(void)downDutyDeal:(void(^)(NSDictionary *dic))block{
    [self excuteAction:[self wrapSignParams:nil] urlMethod:@"courier/downDutyDeal.json" block:block];
}

-(void)rushOrderListWithLocation:(NSString *)clocation  block:(void(^)(NSDictionary *dic))block{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:clocation,@"clocation", nil];
    [self excuteAction:dic urlMethod:@"rushOrderList.json" block:block];
}

-(void)netSendAvailable:(void(^)(NSDictionary *dic))block{
    [self excuteAction:[self wrapSignParams:nil] urlMethod:@"netSendAvailable.json" block:block];
}

//我的订单
-(void)myOrderList:(void(^)(NSDictionary *dic))block{
    [self excuteAction:[self wrapSignParams:nil] urlMethod:@"myOrder.json" block:block];
}

//TODO:public method

-(void)excuteAction:(NSDictionary *)param urlMethod:(NSString *)urlMethodName block:(void(^)(NSDictionary *dic))block{
    NSDictionary * newParams = [self wrapParams:param urlMethodName:urlMethodName block:block];
    if ([newParams count]) {
        [self performTarget:kCTMediatorConnectionTarget action:kCTMediatorConnectionAction params:newParams shouldCacheTarget:NO];
    }
}


-(NSDictionary *)wrapSignParams:(NSDictionary *)params{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    if ([params count]) {
        [dic addEntriesFromDictionary:params];
    }
    [dic setObject:[AppUtility shareInstance].user.courierId forKey:@"courierId"];
    
    
    [dic setObject:[AppUtility shareInstance].user.token forKey:@"token"];
    [dic setObject:[[UIDevice currentDevice]macAddress] forKey:@"mobileMac"];
    
    NSString * sign = [self sign:dic];
    [dic setObject:sign forKey:@"sign"];
    return dic;
}
-(NSDictionary *)wrapParams:(NSDictionary *)dic urlMethodName:(NSString *)urlMethodName block:(void(^)(NSDictionary *dic))block{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    if ([dic count]) {
        [params addEntriesFromDictionary:dic];
    }
    [params setObject:[[UIDevice currentDevice]macAddress] forKey:@"mobileMac"];
    NSLog(@"[AppUtility shareInstance].user.courierId---->%@",[AppUtility shareInstance].user.courierId);
    
    [params setNLYObjectForKey:[AppUtility shareInstance].user.courierId forKey:@"userId"];
    if (![params objectForKey:@"token"]) {
        [params setObject:[AppUtility shareInstance].user.token forKey:@"token"];
    }
    
    if (block) {
        [params setObject:block forKey:@"action"];
    }
    
    NSString * url = [NSString stringWithFormat:@"%@%@",kDomainName,urlMethodName];
    [params setObject:url forKey:@"url"];
    return params;
}
-(NSString *)sign:(NSDictionary *)dic{
    NSArray * keys = [[dic allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString * key1,NSString * key2){
        return [key1 compare:key2];
    }];
    //    NSLog(@"keys---->%@",keys);
    NSMutableString * string = [NSMutableString string];
    for (NSInteger i = 0 ; i <[keys count];i ++) {
        NSString * key = [keys objectAtIndex:i];
        [string appendString:[NSString stringWithFormat:@"%@=%@",key,[dic objectForKey:key]]];
        if (i < [keys count] - 1) {
            [string appendString:@"&"];
        }
    }
    NSLog(@"string------>%@",string);
    //private key
    //    NSString * privateKey = @"I1SWaG";
    
    
    //encode
    NSString * encodeString = [string encodeString:NSUTF8StringEncoding];
    NSLog(@"encodeString---->%@",encodeString);
    //encode md5
    NSString * encodeMD5 = [string md5];
    NSLog(@"encodeMD5------>%@",encodeMD5);
    return encodeMD5;
    
    //    NSString * finalString = [NSString stringWithFormat:@"%@%@",encodeMD5,privateKey];
    //    NSString * finalMD5 = [finalString md5];
    //    return finalMD5;
}


@end
